package com.example.newproject_overseas.Screen


import android.content.Context
import android.util.Log
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.ScrollableDefaults
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.absoluteOffset
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.example.newproject_overseas.R
import com.example.newproject_overseas.components.BottomInputBar
import com.example.newproject_overseas.components.TopApp
import com.example.newproject_overseas.model.entity.ChatMessage
import com.example.newproject_overseas.model.entity.ChatViewModel
import com.example.newproject_overseas.ui.theme.BaseElementComposeTheme
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun AskQuestionsChat(navController: NavHostController,viewModel: ChatViewModel) {
    val chat = viewModel.chatMessages.value;
    val coroutineScope = rememberCoroutineScope()
    val listState = rememberLazyListState()

    //获取弹出键盘的键盘高度
    var keyboardHeight = KeyboardHeightExample()
    Log.e(keyboardHeight.toString(), "keyboardHeight: ", )
    //点击其他屏幕隐藏键盘
    val keyboardController = LocalSoftwareKeyboardController.current
    val focusManager = LocalFocusManager.current

    // 获取当前屏幕高度
    val screenHeight = with(LocalDensity.current) {
        LocalConfiguration.current.screenHeightDp.dp
    }
    //androidApi
    val contexts = LocalContext.current ;
    var LocalView = LocalView.current ;

    Column(
        modifier = Modifier
            .clickable(onClick = {
                Log.e("点击了屏幕", "AskQuestionsChat: ", )
                //focusManager.clearFocus() //清除光标

                // 此处使用 Android 平台的 API 隐藏输入法
                val inputMethodManager = contexts.getSystemService(
                    Context.INPUT_METHOD_SERVICE
                ) as? InputMethodManager
                inputMethodManager?.hideSoftInputFromWindow(
                    LocalView.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )

            })
            .fillMaxSize()
            .systemBarsPadding()
            .background(color = Color(0XFFEFF0F3))
    ) {
        if (keyboardHeight != 0.dp){
            Spacer(modifier = Modifier
                .height(if (keyboardHeight == 0.dp) 0.dp else  screenHeight - keyboardHeight  ))
            Spacer(modifier = Modifier
                .height(80.dp));
        }


        //导航1
        TopApp(title = "Ask questions", navController = navController)
        Spacer(modifier = Modifier.height(5.dp))
            ChatList(chat,
                Modifier.weight(1f))
            BottomInputBar(
                onInputListener = { data ->
                    val time = calculateTime()
                    viewModel.addChatMessage(
                        ChatMessage(
                            id = "2",
                            name = "莫再讲",
                            img = "https://lmg.jj20.com/up/allimg/4k/s/02/2109250006343S5-0-lp.jpg",
                            message = data,
                            sender = "Me",
                            time = time
                        )
                    )
                    coroutineScope.launch {
                        // Animate scroll to the first item
                        listState.animateScrollToItem(index = 0)
                    }
                }
            )
    }


    Spacer(modifier = Modifier.height(keyboardHeight))
}

/**
 * 聊天记录*/
@Composable
fun ChatList(chat: List<ChatMessage>, modifier: Modifier){
    val listState = rememberLazyListState()
    // 使用 LaunchedEffect 监听 chat 数据的变化并滚动到底部
    LaunchedEffect(chat) {
        Log.e(chat.size.toString(), "ChatList: ", )
        listState.scrollToItem(chat.size - 1)
    }
    LazyColumn(
        verticalArrangement = Arrangement.spacedBy(10.dp),
        modifier = modifier
            .background(BaseElementComposeTheme.colors.chatPage)
            .padding(top = 10.dp, start = 10.dp, end = 10.dp),
        state = listState
    ){
        items(chat){ message ->
            if (message.sender == "Me"){
                MeMessage(message)
            }else{
                OtherMessage(message)
            }
        }
    }

}

/**
 * 己方
 * 消息在左，图像在右*/
@Composable
fun MeMessage(bean: ChatMessage){
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth(1f),
        horizontalArrangement = Arrangement.End
    ) {
        Row(modifier = Modifier.weight(1f),
            horizontalArrangement= Arrangement.End){
            useText(text = bean.message,
                color = Color.White,
                modifier = Modifier
                    .meBackground(Color(0xFFFFCC00)),
                maxLines = Int.MAX_VALUE)
        }
            Image(painter = painterResource(id = R.drawable.chat2),
                contentDescription = bean.name,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .size(40.dp)
                    .clip(RoundedCornerShape(4.dp)))
//            modifier = Modifier
//                .size(40.dp)
//                .clip(RoundedCornerShape(4.dp))))
//        AsyncImage(
//            model = bean.img,
//            contentDescription = bean.name,
//            contentScale = ContentScale.Crop,
//            modifier = Modifier
//                .size(40.dp)
//                .clip(RoundedCornerShape(4.dp)))

    }

}

/**
 * 对方
 * 消息在右，图像在左*/
@Composable
fun OtherMessage(bean: ChatMessage){
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth(),
        horizontalArrangement = Arrangement.Start
    ) {
        Image(painter = painterResource(id = R.drawable.chat1),
            contentDescription = bean.name,
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(40.dp)
                .clip(RoundedCornerShape(4.dp)))
//        AsyncImage(
//            model = bean.img,
//            contentDescription = bean.name,
//            modifier = Modifier
//                .size(40.dp)
//                .clip(RoundedCornerShape(4.dp)),
//            contentScale = ContentScale.Crop
//        )
        Row(modifier = Modifier.weight(1f),
            horizontalArrangement= Arrangement.End) {
            useText(
                text = bean.message,
                color = BaseElementComposeTheme.colors.textPrimaryMe,
                modifier = Modifier.otherBackground(BaseElementComposeTheme.colors.bubbleOthers),
                maxLines = Int.MAX_VALUE
            )
        }
    }
}


/**
 * 我发的气泡消息背景*/
fun Modifier.meBackground(color: Color):Modifier = this
    .drawBehind {
        val bubble = Path().apply {
            val rect = RoundRect(
                10.dp.toPx(),
                0f,
                size.width - 10.dp.toPx(),
                size.height,
                4.dp.toPx(),
                4.dp.toPx()
            )
            addRoundRect(rect)
            moveTo(size.width - 10.dp.toPx(), 15.dp.toPx())
            lineTo(size.width - 5.dp.toPx(), 20.dp.toPx())
            lineTo(size.width - 10.dp.toPx(), 25.dp.toPx())
            close()
        }
        drawPath(bubble, color)
    }
    .padding(20.dp, 10.dp)


/**
 * 其他人发的气泡消息背景*/
fun Modifier.otherBackground(color: Color):Modifier = this
    .drawBehind {
        val bubble = Path().apply {
            val rect = RoundRect(
                10.dp.toPx(),
                0f,
                size.width - 10.dp.toPx(),
                size.height,
                4.dp.toPx(),
                4.dp.toPx()
            )
            addRoundRect(rect)
            moveTo(10.dp.toPx(), 15.dp.toPx())
            lineTo(5.dp.toPx(), 20.dp.toPx())
            lineTo(10.dp.toPx(), 25.dp.toPx())
            close()
        }
        drawPath(bubble, color)
    }
    .padding(20.dp, 10.dp)



/**
 * 获取系统当前时间，并转为对应格式*/
fun calculateTime():String{
    val time = System.currentTimeMillis()
    val date = Date(time)
    val format = SimpleDateFormat("HH:mm", Locale.getDefault())
    return format.format(date)
}


/**
 * Image的Text*/
@Composable
fun useText(text: String, modifier: Modifier = Modifier, fontSize: Int = 12, maxLines:Int = 1, color: Color = Color.Black, fontWeight: FontWeight = FontWeight.Normal, textAlign: TextAlign = TextAlign.Start){
    Text(
        text = text,
        fontSize = fontSize.sp,
        color = color,
        fontWeight = fontWeight,
        maxLines = maxLines,
        overflow = TextOverflow.Ellipsis,
        modifier = modifier,
        textAlign = textAlign,
        softWrap = true,
    )
}


/**
 * 获取键盘高度
 * */
@Composable
fun KeyboardHeightExample(): Dp {
    var keyboardHeight by remember { mutableStateOf(0) }

    val rootView = LocalView.current
    val context = LocalContext.current

    val rootViewObserver = rememberUpdatedState(rootView)

    val onGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
        val insets = ViewCompat.getRootWindowInsets(rootView)
        val isKeyboardVisible = insets?.isVisible(WindowInsetsCompat.Type.ime()) == true

        if (isKeyboardVisible) {
            val rect = android.graphics.Rect()
            rootView.getWindowVisibleDisplayFrame(rect)
            val screenHeight = rootView.height
            val newKeyboardHeight = screenHeight - rect.bottom
            if (newKeyboardHeight != keyboardHeight) {
                keyboardHeight = newKeyboardHeight
            }
        } else {
            keyboardHeight = 0
        }
    }

    DisposableEffect(rootViewObserver.value) {
        val viewTreeObserver = rootView.viewTreeObserver
        viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)

        onDispose {
            viewTreeObserver.removeOnGlobalLayoutListener(onGlobalLayoutListener)
        }
    }

    // 返回键盘高度的 Dp
    return keyboardHeight.dp;
}


@Preview
@Composable
fun AskQuestionsChatPreview() {
    val navController = rememberNavController()
    val chatModel = ChatViewModel()
    AskQuestionsChat(navController,chatModel)
}

